<?php

 /**
  * @package JooS
  * @subpackage PHPackager
  */

  require_once "JooS/PHPackager/DOM/Element.php";

  class JooS_PHPackager_DOM_Element_Tasks extends JooS_PHPackager_DOM_Element {
    private $_pi = array();

    /**
     * @return string
     */
    private function getFunctionName() {
      return "_" . strtolower($this->getNode()->tagName);
    }

    /**
     * @return string
     */
    public function getCompiledCode() {
      $compiledCode = array();

      if (sizeof($this->_pi)) {
        $compiledCode[] = "switch (\$stage) {";

        foreach ($this->_pi as $pi) {
          $pi_PHPCode = trim($pi->getCompiledCode());
          if ($pi_PHPCode) {
            $compiledCode[] = "   case '" . $pi->getNode()->target . "':";
            $compiledCode[] = "      " . $pi_PHPCode;
            $compiledCode[] = "      " . "break;";
          }
        }
        $compiledCode[] = "}";
      }
      return implode("\n", $compiledCode);
    }

    /**
     * @return JooS_PHPackager_DOM_Element_Tasks
     */
    public function make() {
      $this->_pi = $this->query("processing-instruction()", "JooS_PHPackager_DOM_ProcessingInstruction_Build");
      foreach ($this->_pi as $pi)
        $pi->make();

      return $this;
    }

    /**
     * @return JooS_PHPackager_DOM_Element_Tasks
     */
    public function install() {
      require_once "JooS/Event.php";
      require_once "JooS/CodeGenerator/Parameter.php";
      require_once "JooS/CodeGenerator/Method.php";
      require_once "JooS/PHPackager/DOM/Element/Package.php";

      $newMethod = JooS_CodeGenerator_Method::newInstance( $this->getFunctionName() )
        ->setVisibility( JooS_CodeGenerator_Method::VISIBILITY_PUBLIC )
        ->setBody( $this->getCompiledCode() )
        ->addParameter( JooS_CodeGenerator_Parameter::newInstance("stage") );
      
      JooS_Event::newInstance(JooS_PHPackager_DOM_Element_Package::EVENT_NEW_METHOD)->notify($newMethod);

      return $this;
    }
  }
